<template>
    <div class="wrap-table">
        <el-form class="clearfix">
            <el-button type="primary" @click="addChild" class="pull-right mg-lr-20 pd-bt">添加文件</el-button>
            <el-button type="primary" @click="addParent" class="pull-right mg-lr-20 pd-bt">添加目录</el-button>
        </el-form>

        <div class="file_content clearfix">
            <div class="file_left_list">
                <template>
                    <el-table  ref="multipleTable" @cell-click="cellClick" :highlight-current-row="true"  :data="leftData" border empty-text="当前列表为空" v-loading="loading" element-loading-text="加载中" style="width: 100%">
                        <el-table-column min-width="100" align="center" label="目录">
                            <template slot-scope="scope"  >
                                <div class="table_cus">
                                    <p style="text-align: left;margin-left: 5%;font-weight: 700;">{{scope.row.TypeName}}</p>
                                    <p style="text-align: left;margin-left: 5%"><span style="margin-right: 5%">{{scope.row.IsShow |IsShow}}</span> <span style="font-size: 12px;color: #C1C1C1;">适用于{{scope.row.Period |Period}}</span></p>
                                    <el-button size="small" type="text" @click.stop="sortParent(scope.$index, scope.row,-1)"><span class="arrow-top"></span></el-button>
                                    <el-button size="small" type="text" @click.stop="sortParent(scope.$index, scope.row,1)"><span class="arrow-bottom"></span></el-button>
                                    <el-button size="small" type="text" @click="editorParent(scope.$index, scope.row)">修改</el-button>
                                    <el-button size="small" type="text" @click="removeParent(scope.$index, scope.row)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </div>
            <div class="file_right_list">
                <template>
                    <el-table  :data="rightData" border empty-text="当前列表为空" v-loading="loadingTw" element-loading-text="加载中" style="width: 100%">
                        <el-table-column
                                prop="FileName"
                                label="文章标题"
                                align="left"
                                header-align="center"
                                :show-overflow-tooltip="true"
                                min-width="300">
                        </el-table-column>
                        <el-table-column
                                prop="IsShow"
                                label="是否显示"
                                :formatter="IsShow"
                                align="center"
                                min-width="60">
                        </el-table-column>
                        <el-table-column width="200" align="center" label="操作">
                            <template slot-scope="scope">
                                <el-button size="small" type="text" @click="sortChild(scope.$index, scope.row,-1)"><span class="arrow-top"></span></el-button>
                                <el-button size="small" type="text" @click="sortChild(scope.$index, scope.row,1)"><span class="arrow-bottom"></span></el-button>
                                <el-button size="small" type="text" @click="editorChild(scope.$index, scope.row)">修改</el-button>
                                <el-button size="small" type="text" @click="removeChild(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </div>
        </div>
        <el-dialog :title="ParentTitle" :close-on-click-modal="false" :visible.sync="dialogParent">
            <el-form :model="ParentForm" label-position="left" :rules="rules" ref="ParentForm" label-width="120px">
                <el-form-item label="目录标题"  prop="TypeName">
                    <el-input v-model="ParentForm.TypeName" auto-complete="off"  placeholder="请输入目录标题"></el-input>
                </el-form-item>
                <el-form-item label="适用阶段" prop="Period">
                    <el-checkbox-group v-model="Period" @change="changeCops">
                        <el-checkbox label="1">孕前期</el-checkbox>
                        <el-checkbox label="2">怀孕期</el-checkbox>
                        <el-checkbox label="3">儿童期（CH1）</el-checkbox>
                        <el-checkbox label="4">儿童期（CH2）</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="是否显示">
                    <el-select v-model="ParentForm.IsShow" clearable placeholder="请选择">
                        <el-option label="是" value="1">
                        </el-option>
                        <el-option label="否" value="2"></el-option>
                    </el-select>

                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogParent = false">取 消</el-button>
                <el-button type="primary" @click="sureParent('ParentForm')">保 存</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="ChildTitle" :close-on-click-modal="false" :visible.sync="dialogChild">
            <el-form :model="ChildForm" label-position="left" :rules="rulesChil" ref="ChildForm" label-width="120px">
                <el-form-item label="文件类型">
                    <el-radio-group v-model="checkNumber">
                        <el-radio label="1">上传PDF</el-radio>
                        <el-radio label="2">视频</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="上传文件" v-if="checkNumber == '1'">
                    <el-upload
                            class="upload-demo"
                            :action="PostFiles"
                            :auto-upload="true"
                            :on-preview="watchFilelist"
                            :on-success="handlePreview"
                            :on-remove="removeDi"
                            :before-upload="beforeAvatarUpload"
                            :multiple="false"
                            :limit="1"
                            :on-exceed="handleExceed"
                            :file-list="fileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <!--<span style="margin-left: 50px;color: #999;">支持pdf格式文件</span>-->
                    </el-upload>
                </el-form-item >
                <el-form-item label="视频地址" prop="FilePath" v-if="checkNumber == '2'">
                    <el-input v-model="ChildForm.FilePath" auto-complete="off"  placeholder="请输入视频地址"></el-input>
                </el-form-item>
                <el-form-item label="文章标题"  prop="FileName">
                    <el-input v-model="ChildForm.FileName" auto-complete="off"  placeholder="请输入文章标题"></el-input>
                </el-form-item>
                <el-form-item label="目录所属" prop="FileTypeId">
                    <el-select v-model="ChildForm.FileTypeId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in options1"
                                :key="item.value"
                                :label="item.TypeName"
                                :value="item.SYS_ID">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否显示">
                    <el-select v-model="ChildForm.IsShow" clearable placeholder="请选择">
                        <el-option label="是" value="1">
                        </el-option>
                        <el-option label="否" value="2"></el-option>
                    </el-select>
                    <!--<el-switch-->
                            <!--v-model="ChildForm.IsShow"-->
                            <!--active-color="#13ce66"-->
                            <!--active-text="显示"-->
                            <!--inactive-text="不显示"-->
                            <!--active-value="1"-->
                            <!--inactive-value="2"-->
                            <!--inactive-color="#ff4949">-->
                    <!--</el-switch>-->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogChild = false">取 消</el-button>
                <el-button type="primary" @click="sureChild('ChildForm')">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {dateFunction} from '@/utils/index'
export default{
    data (){
        return {
            leftData:[],
            loading:true,
            loadingTw:true,
            rightData:[],
	        checkNumber:'1',
            dialogParent:false,
            ParentTitle:'添加目录',
            Period:[],
            rules: {
                TypeName: [
                    { required: true,  message: "必填项", trigger: "blur" }
                ],
                Period: [
                    { required: true,  message: "必填项", trigger: "blur" }
                ],
            },
            rulesChil:{
                FileName: [
                    { required: true,  message: "必填项", trigger: "blur" }
                ],
                FileTypeId: [
                    { required: true,  message: "必填项", trigger: "blur" }
                ],
	            FilePath:[
		            { required: true,  message: "必填项", trigger: "blur" }
                ]
            },
            ParentForm:{
                Period:[],
                TypeName:'',
                IsShow:'1'
            },
            rowOff:false,
            chlOff:false,
            ChildTitle:'添加文件',
            dialogChild:false,
            ChildForm:{
                FileName:'',
                IsShow:'1',
                FileTypeId:'',
                FileData:'',
                Suffix:'pdf',
                FileSize:'',
                FilePath:''
            },
            options1:[],
            fileList:[],
            IsShow(row, column, cellValue, index){
                return cellValue=='1'?'显示':'不显示'
            },
            PostFiles:actions()
        }
    },
    computed:{

    },
    filters:{
        IsShow:function(val){
            return val=='1'?'显示':'不显示'
        },
        Period:function(val){
            let arr=[];
            let str=val.split(',')
            for(let i of str){
                if(i=='1'){
                    arr.push('孕前期')
                }
                else if(i=='2'){
                    arr.push('怀孕期')
                }
                else if(i=='3'){
                    arr.push('儿童期（CH1）')
                }
                else{
                    arr.push('儿童期（CH2）')
                }
            }
            return arr.join(',')
        }
    },
    methods:{
        sortChild:function(index,row,dir){   //文件排序
            let that=this;
            let nowIndex=''
            let arr=[]
            nowIndex=row.SortIndex
            let oterRow=''
            if (dir == 1) {  //向下
                if (index >= that.rightData.length - 1) {
                    return;
                }
                oterRow=that.rightData[index+1]
                row.SortIndex=oterRow.SortIndex
                oterRow.SortIndex=nowIndex
            } else {
                if (index <=0) {
                    return;
                }                    //向上
                oterRow=that.rightData[index-1]
                row.SortIndex=oterRow.SortIndex
                oterRow.SortIndex=nowIndex
            }
            if(oterRow!==''){
                arr.push(oterRow)
                arr.push(row)
                that.loadingTw=true
                that.service({
                    url: "/Dic/SaveFileIndex",
                    method: "post",
                    data: {
                        listFile:arr
                    }
                }).then(response => {
                    that.rightData.splice(index,1)
                    that.rightData.splice(index+dir,0,row)
                    that.loadingTw=false
                }).catch(data => {
                    that.loadingTw=false
                });
            }

        },
        sortParent:function(index,row,dir){    //目录排序
            let that=this;
            let nowIndex=''
            let arr=[]
            nowIndex=row.SortIndex
            let oterRow=''
            if (dir == 1) {  //向下
                if (index >= that.leftData.length - 1) {
                    return;
                }
                oterRow=that.leftData[index+1]
                row.SortIndex=oterRow.SortIndex
                oterRow.SortIndex=nowIndex
            } else {
                if (index <=0) {
                    return;
                }                    //向上
                oterRow=that.leftData[index-1]
                row.SortIndex=oterRow.SortIndex
                oterRow.SortIndex=nowIndex
            }
            if(oterRow!==''){
                arr.push(oterRow)
                arr.push(row)
                that.loading=true
                that.service({
                    url: "/Dic/SaveFileTypeIndex",
                    method: "post",
                    data: {
                        listFileType:arr
                    }
                }).then(response => {
                    that.leftData.splice(index,1)
                    that.leftData.splice(index+dir,0,row)
                    that.loading=false
                }).catch(data => {
                    that.loading=false
                });
            }

        },
        editorChild:function(index,row){     //修改文件
            let that=this;
            console.log(row)
            that.fileList=[{
                name:row.FileName,
                url:row.FilePath
            }]
            that.ChildTitle="修改文件"
            that.ChildForm={
                FileName:'',
                IsShow:'1',
                FileTypeId:'',
                FileData:'',
                Suffix:'pdf',
                FileSize:'',
                FilePath:''
            };
            if(row.FilePath.indexOf('mp4') >-1){
                that.checkNumber = '2'
            }
            else{
            	that.checkNumber = '1'
            }
            that.ChildForm=JSON.parse(JSON.stringify(row))
            that.rowOff=false;
            that.dialogChild=true;
        },
        editorParent:function(index,row){     //修改目录
            let that=this;
            that.ParentTitle="修改目录";
            that.ParentForm={
                Period:[],
                TypeName:'',
                IsShow:'1'
            };
            that.ParentForm=JSON.parse(JSON.stringify(row))
            that.Period=row.Period.split(',')
            that.rowOff=false;
            that.dialogParent=true;
        },
        removeParent:function(index,row){    //删除目录
            let that=this;
            that.$confirm('此操作将删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                that.service({
                    url: "/Dic/DeleteFileType",
                    method: "post",
                    data: {
                        ...row
                    }
                }).then(response => {
                    that.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    that.getList()
                }).catch(data => {

                });
                }).catch(() => {
                that.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        removeChild(index,row){    //删除文件
            let that=this;
            that.$confirm('此操作将删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                that.service({
                    url: "/Dic/DeleteFile",
                    method: "post",
                    data: {
                        ...row
                    }
                }).then(response => {
                    that.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    that.getList()
                }).catch(data => {
                });

            }).catch(() => {
                that.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        cellClick:function(row){  //点击单元格
            let that=this;
            that.getChildList(row.SYS_ID)
        },
        changeCops:function(val){  //多选框
            this.ParentForm.Period=val.join(',')
        },
        watchFilelist:function(file){  //点击文件
            let httpL=''
            window.location.href.indexOf('https')>=0? httpL='https://': httpL='http://'
            let httpName=httpL+window.location.host+'/';
            window.open(httpName+file.url)
        },
        beforeAvatarUpload:function(files){  //上传之前的钩子
            let isVideo = (
                ['application/pdf'].indexOf(files.type) == -1)
            if(isVideo){
                this.$message.error('目前仅支持PDF!');
                this.fileList=[]
            }
            return !isVideo
        },
        removeDi:function(){
            this.fileList=[]
        },
        handlePreview(response,file) {   //添加文件回调
        	console.log(response)
            let that=this;
            let data=JSON.parse(response);
            that.ChildForm.FilePath=data.msg;
            that.ChildForm.FileSize=(file.size/1024/1024).toFixed(2)+'MB'
            that.ChildForm.FileName=file.name.split('.')[0]
            that.fileList=[{
                name:that.ChildForm.FileName,
                url:that.ChildForm.FilePath
            }]
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        addParent:function(){   //添加目录
            let that=this;
            that.rowOff=false;
            that.ParentTitle="添加目录";
            that.dialogParent=true;
            that.Period=[];
            that.checkNumber = '1'
            that.ParentForm={
                Period:[],
                TypeName:'',
                IsShow:'1'
            };
            that.$nextTick(function () {
                that.$refs['ParentForm'].resetFields();
            })
        },
        addChild:function(){  //添加文件
            let that=this;
            that.rowOff=false;
            that.dialogChild=true;
            that.$nextTick(function () {
                that.ChildForm={
                    FileName:'',
                    IsShow:'1',
                    FileTypeId:'',
                    FileData:'',
                    Suffix:'pdf',
                    FileSize:'',
                    FilePath:''
                };
                that.ChildTitle="添加文件"
                that.fileList=[]
                that.$refs['ChildForm'].resetFields();
            })
        },
        sureChild:function(formName){  //文件确定
            let that=this;
            if(that.rowOff){
                return false
            }
            that.rowOff=true
            that.$refs[formName].validate((valid) =>{
                if (valid) {
                    if( that.fileList.length==0 && that.checkNumber == '1'){
                        that.$message.warning('请选择上传文件')
                        that.rowOff=false
                        return false
                    }
                    that.ChildForm.UpdateTime=dateFunction("yyyy-MM-dd hh:mm:ss",new Date())
                    that.service({
                        url: "/Dic/SaveFile",
                        method: "post",
                        data: {
                            ...that.ChildForm,
                        }
                    }).then(response => {
                        that.dialogChild=false
                        that.getList()
                    }).catch(data => {
                        that.rowOff=false
                    });
                }
            else{
                    that.rowOff=false
                    return false
                }
            })
        },
        sureParent:function(formName){  //目录确定
            let that=this;
            if(that.rowOff){
                return false
            }
            that.rowOff=true
            that.$refs[formName].validate((valid) =>{
                if (valid) {
                    that.service({
                        url: "/Dic/SaveFileType",
                        method: "post",
                        data: {
                            ...that.ParentForm,
                        }
                     }).then(response => {
                            that.dialogParent=false;
                            that.getList()
                     }).catch(data => {
                        that.rowOff=false
                     });
                 }
                else{
                     that.rowOff=false
                     return false
                    }
            })
        },
        getList:function(){           //获取一级信息列表
            let that=this
            that.loading=true
            that.service({
                url:'/Dic/GetFileType',
                method:'get',
                params:{
                    isApp:'0'
                }
            }).then(response=>{
                that.leftData=response.dtData
                if(response.dtData.length>0){
                    that.getChildList(response.dtData[0].SYS_ID)
                }
                else{
                    that.getChildList('123456')
                }
                that.options1=response.dtData
                that.$refs.multipleTable.setCurrentRow(that.leftData[0]);
                that.loading=false
            }).catch(data=>{
                that.loading=false
            })
        },
        getChildList:function(typeId){           //获取二级信息列表
            let that=this
            that.loadingTw=true
            that.service({
                url:'/Dic/GetFile',
                method:'get',
                params:{
                    isApp:'0',
                    typeId:typeId
                }
            }).then(response=>{
                that.rightData=response.dtData
                that.loadingTw=false
            }).catch(data=>{
                that.loadingTw=false
            })
        },
    },
    mounted:function(){
        let that=this;
        that.getList()
    }
}
    function actions(){
        let httpL=''
        if(window.location.href.indexOf('https')>=0){
            httpL='https://'
        }
        else{
            httpL='http://'
        }
        let httpName=httpL+window.location.host;
        let BASE_API='http://localhost:1442/api';
        if(httpName.indexOf('localhost')==-1){
            BASE_API=httpName+'/API/105/api/'
        }
        return BASE_API+'/Dic/PostFiles'
    }
</script>
<style scoped lang="scss">
    .file_content{
        margin-top: 20px;
        .file_left_list{
            width: 30%;
            float: left;
            margin-right: 0px;
            .table_cus{
                text-align: right;
                cursor: pointer;
                button{

                }
            }

        }
        .file_right_list{
            float: left;
            width: 70%;
        }
    }
    .arrow-top {
        position: relative;
        display: inline-block;
        box-sizing: border-box;
        width: 8px;
        height: 8px;
        border: 1px solid #409eff;
        border-width: 1px 0 0 1px;
        transform: rotate(45deg) translateY(-50%);
    &::before {
         content: "";
         position: absolute;
         height: 1px;
         width: 12px;
         background-color: #409eff;
         left: 0;
         top: -1px;
         transform: rotate(45deg);
         transform-origin: 0 0;
     }
    }

    .arrow-bottom {
        position: relative;
        display: inline-block;
        box-sizing: border-box;
        width: 8px;
        height: 8px;
        border: 1px solid #409eff;
        border-width: 0 1px 1px 0;
        transform: rotate(45deg);
    &::before {
         content: "";
         position: absolute;
         height: 1px;
         width: 12px;
         background-color: #409eff;
         right: 0;
         bottom: 0;
         transform: rotate(45deg);
         transform-origin: 100% 0;
     }
    }

</style>